<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>情侣空间 - 爱情纪念日</title>
    <script src="/Style/js/tailwindcss.js"></script>
    <link href="/Style/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#ec4899',
                        secondary: '#fce7f3',
                    }
                }
            }
        }


    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
        }


    </style>
</head>
<body class="bg-gray-50 font-sans">
<!-- 导航栏 -->
<nav class="bg-white shadow-md fixed w-full top-0 z-50">
    <div class="container mx-auto px-4 py-3">
        <div class="flex justify-between items-center">
            <div class="flex items-center">
                <i class="fa fa-heart text-primary text-2xl mr-2"></i>
                <span class="text-xl font-bold text-gray-800">爱情纪念日</span>
            </div>

            <div class="hidden md:flex space-x-8"><a href="/" class="text-dark hover:text-primary transition-colors py-2">首页</a>
            <a href="/moments" class="text-dark hover:text-primary transition-colors py-2">点点滴滴</a>
            <a href="/photos" class="text-dark hover:text-primary transition-colors py-2">Love Photo</a>
            <a href="/lovelist" class="text-dark hover:text-primary transition-colors py-2">Love List</a>
            <a href="/messages" class="text-dark hover:text-primary transition-colors py-2">留言板</a>
            <a href="/couple" class="text-dark hover:text-primary transition-colors py-2">爱情纪念</a>
            </div>

            <div class="flex items-center space-x-4">
                <div class="relative">
                    <button id="user-menu-button" class="flex items-center space-x-2 focus:outline-none">
                        <img id="user-menu-touxiang"
                             src="{{ session.avatar if session.avatar else '/default_avatar.jpg' }}"
                             alt="用户头像" class="w-8 h-8 rounded-full object-cover border-2 border-primary"
                             onerror="this.src='https://picsum.photos/200/200?random=1'">
                        <span class="hidden md:inline text-gray-700">{{ session.nickname }}</span>
                        <i class="fa fa-chevron-down text-xs text-gray-500"></i>
                    </button>
                    <div id="profile-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">


                    <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6 transform transition-all">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-lg font-medium text-gray-900">个人资料</h3>
                            <button id="close-modal" class="text-gray-400 hover:text-gray-500">
                                <span class="sr-only">关闭</span>
                                <svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>

                        <div class="space-y-4">
                            <div>
                                <label for="nickname" class="block text-sm font-medium text-gray-700">昵称</label>
                                <input type="text" id="nickname" name="nickname"
                                       class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                                       value="">
                            </div>

                            <div class="pt-4 flex justify-end">
                                <button id="save-profile" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                    保存修改
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                    <div id="user-menu"
                         class="hidden absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-10">
                        <a href="#"  id="open-profile" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">个人资料</a>
                        <a href="/logout" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">退出登录</a>
                    </div>
                </div>
                <button id="mobile-menu-button" class="md:hidden text-gray-700">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </div>

        <!-- 移动端菜单 -->
        <div id="mobile-menu" class="hidden md:hidden mt-4 pb-2">
            <a href="/" class="block text-dark hover:text-primary transition-colors py-2">首页</a>
            <a href="/moments" class="block text-dark hover:text-primary transition-colors py-2">点点滴滴</a>
            <a href="/photos" class="block text-dark hover:text-primary transition-colors py-2">Love Photo</a>
            <a href="/lovelist" class="block text-dark hover:text-primary transition-colors py-2">Love List</a>
            <a href="/messages" class="block text-dark hover:text-primary transition-colors py-2">留言板</a>
            <a href="/couple" class="block text-primary font-medium py-2">爱情纪念</a>
        </div>
    </div>
</nav>

<!-- 主内容 -->
<main class="container mx-auto px-4 pt-24 pb-16">
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 情侣关系状态 -->
        <div class="lg:col-span-1">
            <div class="bg-white rounded-xl shadow-md p-6 h-full">
                <h2 class="text-xl font-semibold text-gray-800 mb-6">情侣关系</h2>

                <div id="no-relationship" class="text-center py-6">
                    <div class="w-20 h-20 bg-secondary rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fa fa-heart-o text-primary text-3xl"></i>
                    </div>
                    <p class="text-gray-600 mb-4">你还没有绑定情侣关系</p>
                    <button id="send-request-btn"
                            class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-colors">
                        <i class="fa fa-user-plus mr-2"></i>绑定情侣
                    </button>
                </div>

                <div id="in-relationship" class="hidden">
                    <div class="text-center mb-6">
                        <div class="flex items-center justify-center space-x-4 mb-4">
                            <div class="text-center">
                                <img id="my-avatar" src="/default_avatar.jpg"
                                     alt="我的头像"
                                     class="w-16 h-16 rounded-full object-cover border-2 border-primary mx-auto mb-2"
                                     onerror="this.src='https://picsum.photos/200/200?random=2'">
                                <p class="font-medium">{{ session.nickname }}</p>
                            </div>
                            <div class="text-2xl text-primary">
                                <i class="fa fa-heart"></i>
                            </div>
                            <div class="text-center">
                                <img id="partner-avatar" src="" alt="伴侣侣头像"
                                     class="w-16 h-16 rounded-full object-cover border-2 border-primary mx-auto mb-2"
                                     onerror="this.src='https://picsum.photos/200/200?random=3'">
                                <p id="partner-name" class="font-medium"></p>
                            </div>
                        </div>
                        <p class="text-gray-600">
                            你们已经绑定关系 <span id="days-together" class="font-semibold text-primary"></span> 天了
                        </p>
                    </div>

                    <div class="border-t border-gray-100 pt-4">
                        <button id="end-relationship-btn"
                                class="w-full text-red-500 hover:text-red-600 font-medium py-2 border border-red-200 rounded-lg hover:bg-red-50 transition-colors">
                            <i class="fa fa-heart-broken mr-2"></i>解除关系
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 情侣请求和互动 -->
        <div class="lg:col-span-2">
            <div class="bg-white rounded-xl shadow-md p-6 mb-8">
                <h2 class="text-xl font-semibold text-gray-800 mb-6">情侣请求</h2>

                <div class="mb-8">
                    <h3 class="text-lg font-medium text-gray-700 mb-4">收到的请求</h3>
                    <div id="received-requests" class="space-y-4">
                        <!-- 收到的请求将通过JS动态加载 -->
                        <div class="text-center text-gray-500 py-6" id="no-received-requests">
                            暂无收到的情侣请求
                        </div>
                    </div>
                </div>

                <div>
                    <h3 class="text-lg font-medium text-gray-700 mb-4">发送的请求</h3>
                    <div id="sent-requests" class="space-y-4">
                        <!-- 发送的请求将通过JS动态加载 -->
                        <div class="text-center text-gray-500 py-6" id="no-sent-requests">
                            暂无发送的情侣请求
                        </div>
                    </div>
                </div>
            </div>

            <!-- 共同纪念日 -->
            <div class="bg-white rounded-xl shadow-md p-6">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-xl font-semibold text-gray-800">共同纪念日</h2>
                    <button id="add-shared-anniversary"
                            class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-colors flex items-center">
                        <i class="fa fa-plus mr-2"></i>添加纪念日
                    </button>
                </div>

                <!-- 纪念日列表 -->
                <div id="anniversaries-container" class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- 加载状态 -->
                    <div id="loading-anniversaries" class="col-span-full text-center py-12">
                        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-4"></div>
                        <p class="text-gray-500">加载共同纪念日中...</p>
                    </div>

                    <!-- 空状态 -->
                    <div id="no-anniversaries" class="col-span-full text-center py-12 hidden">
                        <div class="w-20 h-20 bg-secondary rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fa fa-calendar-o text-primary text-3xl"></i>
                        </div>
                        <p class="text-gray-600 mb-4">你们还没有共同的纪念日</p>
                        <button id="add-first-anniversary"
                                class="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg transition-colors">
                            <i class="fa fa-plus mr-2"></i>添加第一个纪念日
                        </button>
                    </div>

                    <!-- 纪念日卡片将通过JS动态加载 -->
                </div>
            </div>
        </div>
    </div>
</main>

<!-- 添加/编辑纪念日模态框 -->
<div id="anniversary-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-lg w-full max-w-lg mx-4 p-6 transform transition-all">
        <h3 id="modal-title" class="text-xl font-bold text-gray-800 mb-4">添加共同纪念日</h3>

        <form id="anniversary-form">
            <input type="hidden" id="anniversary-id">

            <div class="mb-4">
                <label for="title" class="block text-gray-700 mb-2">纪念日名称 <span class="text-red-500">*</span></label>
                <input type="text" id="title"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                       placeholder="例如：第一次约会、确立关系">
            </div>

            <div class="mb-4">
                <label for="date" class="block text-gray-700 mb-2">日期 <span class="text-red-500">*</span></label>
                <input type="date" id="date"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
            </div>

            <div class="mb-4">
                <label for="type" class="block text-gray-700 mb-2">类型</label>
                <select id="type"
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                    <option value="">请选择类型</option>
                    <option value="love_start">关系确定日</option>
                    <option value="爱情">爱情</option>
                    <option value="生活">生活</option>
                    <option value="旅行">旅行</option>
                    <option value="其他">其他</option>
                </select>
            </div>

            <div class="mb-6">
                <label for="description" class="block text-gray-700 mb-2">描述</label>
                <textarea id="description" rows="3"
                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                          placeholder="添加一些描述，记录这个特别的日子..."></textarea>
            </div>

            <div class="flex justify-end space-x-3">
                <button type="button" id="cancel-anniversary"
                        class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                    取消
                </button>
                <button type="submit"
                        class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">保存
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 发送情侣请求模态框 -->
<div id="request-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-lg w-full max-w-md mx-4 p-6 transform transition-all">
        <h3 class="text-xl font-bold text-gray-800 mb-4">发送情侣请求</h3>

        <form id="request-form">
            <div class="mb-4">
                <label for="receiver-username" class="block text-gray-700 mb-2">对方账号</label>
                <input type="text" id="receiver-username"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                       placeholder="请输入对方的账号">
            </div>

            <div class="mb-6">
                <label for="request-message" class="block text-gray-700 mb-2">留言</label>
                <textarea id="request-message" rows="3"
                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                          placeholder="请输入想对对方说的话...">我想和你成为情侣，一起记录我们的美好时光。</textarea>
            </div>

            <div class="flex justify-end space-x-3">
                <button type="button" id="cancel-request"
                        class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                    取消
                </button>
                <button type="submit"
                        class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">发送请求
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 确认删除模态框 -->
<div id="delete-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-lg w-full max-w-md mx-4 p-6">
        <h3 class="text-xl font-bold text-gray-800 mb-4">确认删除</h3>
        <p class="text-gray-600 mb-6">确定要删除这个纪念日吗？此操作不可撤销。</p>

        <input type="hidden" id="delete-anniv-id">

        <div class="flex justify-end space-x-3">
            <button id="cancel-delete"
                    class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                取消
            </button>
            <button id="confirm-delete"
                    class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors">确认删除
            </button>
        </div>
    </div>
</div>

<!-- 确认解除关系模态框 -->
<div id="confirm-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-lg w-full max-w-md mx-4 p-6">
        <h3 class="text-xl font-bold text-gray-800 mb-4">确认解除关系</h3>
        <p class="text-gray-600 mb-6">确定要解除情侣关系吗？此操作不可撤销。</p>

        <div class="flex justify-end space-x-3">
            <button id="cancel-confirm"
                    class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors">
                取消
            </button>
            <button id="confirm-end"
                    class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors">确认解除
            </button>
        </div>
    </div>
</div>

<!-- 通知提示 -->
<div id="notification"
     class="fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50">
    <i id="notification-icon" class="mr-2"></i>
    <span id="notification-message"></span>
</div>

<script>
        // DOM元素
        const noRelationshipEl = document.getElementById('no-relationship');
        const inRelationshipEl = document.getElementById('in-relationship');
        const partnerAvatarEl = document.getElementById('partner-avatar');
        const partnerNameEl = document.getElementById('partner-name');
        const daysTogetherEl = document.getElementById('days-together');
        const receivedRequestsEl = document.getElementById('received-requests');
        const sentRequestsEl = document.getElementById('sent-requests');
        const noReceivedRequestsEl = document.getElementById('no-received-requests');
        const noSentRequestsEl = document.getElementById('no-sent-requests');

        // 纪念日相关元素
        const anniversariesContainer = document.getElementById('anniversaries-container');
        const loadingAnniversaries = document.getElementById('loading-anniversaries');
        const noAnniversaries = document.getElementById('no-anniversaries');

        // 模态框元素
        const anniversaryModal = document.getElementById('anniversary-modal');
        const deleteModal = document.getElementById('delete-modal');
        const requestModal = document.getElementById('request-modal');
        const confirmModal = document.getElementById('confirm-modal');
        const anniversaryForm = document.getElementById('anniversary-form');
        const requestForm = document.getElementById('request-form');
        const modalTitle = document.getElementById('modal-title');

        // 页面加载时获取数据
        document.addEventListener('DOMContentLoaded', function() {
            // 安全地绑定事件监听器，先检查元素是否存在
            const addAnniversaryBtn = document.getElementById('add-shared-anniversary');
            if (addAnniversaryBtn) {
                addAnniversaryBtn.addEventListener('click', () => openAnniversaryModal());
            }

            const addFirstAnniversary = document.getElementById('add-first-anniversary');
            if (addFirstAnniversary) {
                addFirstAnniversary.addEventListener('click', () => openAnniversaryModal());
            }

            const cancelAnniversary = document.getElementById('cancel-anniversary');
            if (cancelAnniversary) {
                cancelAnniversary.addEventListener('click', closeAnniversaryModal);
            }

            const cancelDelete = document.getElementById('cancel-delete');
            if (cancelDelete) {
                cancelDelete.addEventListener('click', closeDeleteModal);
            }

            const confirmDelete = document.getElementById('confirm-delete');
            if (confirmDelete) {
                confirmDelete.addEventListener('click', handleDelete);
            }

            if (anniversaryForm) {
                anniversaryForm.addEventListener('submit', handleSaveAnniversary);
            }

            // 情侣请求相关事件
            document.getElementById('send-request-btn').addEventListener('click', openRequestModal);
            document.getElementById('cancel-request').addEventListener('click', closeRequestModal);
            document.getElementById('end-relationship-btn').addEventListener('click', openConfirmModal);
            document.getElementById('cancel-confirm').addEventListener('click', closeConfirmModal);
            document.getElementById('confirm-end').addEventListener('click', endRelationship);
            requestForm.addEventListener('submit', handleSendRequest);


                 // 用户菜单切换
                const userMenuButton = document.getElementById('user-menu-button');
                const userMenu = document.getElementById('user-menu');
                if (userMenuButton && userMenu) {
                    userMenuButton.addEventListener('click', function(event) {
                        // 阻止事件冒泡，避免触发全局点击事件
                        event.stopPropagation();
                        userMenu.classList.toggle('hidden');
                    });
                }


            // 点击其他地方关闭操作菜单和用户菜单
            document.addEventListener('click', function(event) {
                // 检查点击目标是否是用户菜单按钮或其内部元素
                const isUserMenuButton = event.target.closest('#user-menu-button');
                // 检查点击目标是否是用户菜单或其内部元素
                const isUserMenu = event.target.closest('#user-menu');

                // 如果点击的不是用户菜单按钮或用户菜单本身，则关闭用户菜单
                if (!isUserMenuButton && !isUserMenu) {
                    document.querySelectorAll('.anniversary-actions').forEach(el => {
                        el.classList.add('hidden');
                    });

                    const userMenu = document.getElementById('user-menu');
                    if (userMenu && !userMenu.classList.contains('hidden')) {
                        userMenu.classList.add('hidden');
                    }
                }
            });

                // 移动端菜单切换
                const mobileMenuButton = document.getElementById('mobile-menu-button');
                const mobileMenu = document.getElementById('mobile-menu');
                if (mobileMenuButton && mobileMenu) {
                    mobileMenuButton.addEventListener('click', function(event) {
                        // 同样为移动端菜单添加阻止冒泡
                        event.stopPropagation();
                        mobileMenu.classList.toggle('hidden');
                    });
                }
                // 点击其他地方关闭菜单
                document.addEventListener('click', function() {
                const userMenu = document.getElementById('user-menu');
                if (userMenu && !userMenu.classList.contains('hidden')) {
                    userMenu.classList.add('hidden');
                }

                const mobileMenu = document.getElementById('mobile-menu');
                if (mobileMenu && !mobileMenu.classList.contains('hidden')) {
                    mobileMenu.classList.add('hidden');
                }
            });

            // 加载数据
            initUserAvatar(function(){
				checkRelationshipStatus();
				loadCoupleRequests();
            
            });
            
        });


        let myAvatarUrl = '/default_avatar.jpg'; // 默认值
        // 初始化用户头像，兼容移动端
        function initUserAvatar(callback) {
        fetch('/api/user')
            .then(response => {
                if (!response.ok) throw new Error('获取用户信息失败');
                return response.json();
            })
            .then(user => {

                    myAvatarUrl = user.avatar || '/default_avatar.jpg';
                    document.getElementById('user-menu-touxiang').src = myAvatarUrl;
                    document.getElementById('nickname').value = user.nickname || '';
					// 执行回调函数
					if (callback) callback();
            })
            .catch(error => {
                console.log('获取用户头像失败，使用默认头像:', error);
                // 保持默认头像不变
            });
        }
        
        
        

        // 检查情侣关系状态
        function checkRelationshipStatus() {
            fetch('/api/couple/relationship')
                .then(response => response.json())
                .then(data => {
                    if (data.in_relationship) {
                        // 已建立情侣关系
                        noRelationshipEl.classList.add('hidden');
                        inRelationshipEl.classList.remove('hidden');

                        // 更新伴侣信息
                        partnerAvatarEl.src = data.partner.avatar || '/static/default_avatar.jpg';
                        partnerAvatarEl.alt = data.partner.nickname;
                        partnerNameEl.textContent = data.partner.nickname;
                        daysTogetherEl.textContent = data.relationship.days_together;

                        // 确保我的头像显示当前登录用户的头像
                        const myAvatar = myAvatarUrl;
                        document.getElementById('my-avatar').src = myAvatar;
                        document.getElementById('my-avatar').alt = "{{ session.nickname }}";
                        // 加载共同纪念日
                        loadSharedAnniversaries();
                    } else {
                        // 未建立情侣关系
                        noRelationshipEl.classList.remove('hidden');
                        inRelationshipEl.classList.add('hidden');

                        // 隐藏纪念日加载状态，显示未建立关系提示
                        loadingAnniversaries.classList.add('hidden');
                        noAnniversaries.classList.remove('hidden');
                        noAnniversaries.innerHTML = `
                            <div class="w-20 h-20 bg-secondary rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fa fa-heart-o text-primary text-3xl"></i>
                            </div>
                            <p class="text-gray-600 mb-4">绑定情侣关系后可以添加共同纪念日</p>
                        `;
                    }
                })
                .catch(error => {
                    showNotification('获取关系状态失败', 'error');
                    console.error('Error:', error);
                });
        }

        // 加载情侣请求
        function loadCoupleRequests() {
            fetch('/api/couple/requests')
                .then(response => response.json())
                .then(data => {
                    // 处理收到的请求
                    if (data.received.length > 0) {
                        noReceivedRequestsEl.classList.add('hidden');
                        receivedRequestsEl.innerHTML = '';

                        data.received.forEach(request => {
                            const requestEl = document.createElement('div');
                            requestEl.className = 'p-4 border border-gray-100 rounded-lg flex justify-between items-center';

                            // 根据请求状态显示不同内容
                            let actionButtons = '';
                            if (request.status === 'pending') {
                                actionButtons = `
                                    <div class="flex space-x-2">
                                        <button onclick="respondToRequest(${request.id}, 'accept')" class="px-3 py-1 bg-primary text-white rounded text-sm hover:bg-primary/90">接受</button>
                                        <button onclick="respondToRequest(${request.id}, 'reject')" class="px-3 py-1 border border-gray-300 rounded text-sm hover:bg-gray-100">拒绝</button>
                                    </div>
                                `;
                            } else {
                                const statusText = request.status === 'accepted'
                                    ? '<span class="text-green-500">已接受</span>'
                                    : '<span class="text-red-500">已拒绝</span>';
                                actionButtons = `<div class="text-sm">${statusText}</div>`;
                            }

                            requestEl.innerHTML = `
                                <div class="flex items-center">
                                    <img src="${request.sender_avatar || '/static/default_avatar.jpg'}" alt="${request.sender_name}" class="w-10 h-10 rounded-full mr-3"
                                         onerror="this.src='https://picsum.photos/200/200?random=${Math.random()}'">
                                    <div>
                                        <p class="font-medium">${request.sender_name} 请求与你成为情侣</p>
                                        <p class="text-sm text-gray-500 mt-1">${request.message || '想和你一起记录美好时光'}</p>
                                    </div>
                                </div>
                                ${actionButtons}
                            `;
                            receivedRequestsEl.appendChild(requestEl);
                        });
                    } else {
                        noReceivedRequestsEl.classList.remove('hidden');
                    }

                    // 处理发送的请求
                    if (data.sent.length > 0) {
                        noSentRequestsEl.classList.add('hidden');
                        sentRequestsEl.innerHTML = '';

                        data.sent.forEach(request => {
                            const statusText = {
                                'pending': '<span class="text-yellow-500">等待回应</span>',
                                'accepted': '<span class="text-green-500">已接受</span>',
                                'rejected': '<span class="text-red-500">已拒绝</span>'
                            };

                            const requestEl = document.createElement('div');
                            requestEl.className = 'p-4 border border-gray-100 rounded-lg flex justify-between items-center';
                            requestEl.innerHTML = `
                                <div class="flex items-center">
                                    <img src="${request.receiver_avatar || '/static/default_avatar.jpg'}" alt="${request.receiver_name}" class="w-10 h-10 rounded-full mr-3"
                                         onerror="this.src='https://picsum.photos/200/200?random=${Math.random()}'">
                                    <div>
                                        <p class="font-medium">已向 ${request.receiver_name} 发送请求</p>
                                        <p class="text-sm text-gray-500 mt-1">${statusText[request.status]}</p>
                                    </div>
                                </div>
                                ${request.status === 'pending' ?
                                    `<button onclick="cancelRequest(${request.id})" class="text-red-500 text-sm hover:underline">取消请求</button>` :
                                    ''}
                            `;
                            sentRequestsEl.appendChild(requestEl);
                        });
                    } else {
                        noSentRequestsEl.classList.remove('hidden');
                    }
                })
                .catch(error => {
                    showNotification('获取请求失败', 'error');
                    console.error('Error:', error);
                });
        }

        // 加载共同纪念日
        function loadSharedAnniversaries() {
            if (loadingAnniversaries) loadingAnniversaries.classList.remove('hidden');
            if (noAnniversaries) noAnniversaries.classList.add('hidden');
            if (anniversariesContainer) anniversariesContainer.innerHTML = '';

            // 实际项目中应使用正确的API端点
            fetch('/api/couple/shared-anniversaries')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取纪念日失败');
                    }
                    return response.json();
                })
                .then(data => {
                    if (loadingAnniversaries) loadingAnniversaries.classList.add('hidden');

                    if (data.anniversaries && data.anniversaries.length > 0) {
                        // 按距离下次的天数排序
                        data.anniversaries.sort((a, b) => a.days_until - b.days_until);

                        // 创建纪念日卡片
                        data.anniversaries.forEach(anniversary => {
                            const card = createAnniversaryCard(anniversary);
                            if (anniversariesContainer) {
                                anniversariesContainer.appendChild(card);
                            }
                        });
                    } else if (noAnniversaries) {
                        noAnniversaries.classList.remove('hidden');
                    }
                })
                .catch(error => {
                    if (loadingAnniversaries) loadingAnniversaries.classList.add('hidden');
                    showNotification('获取纪念日失败', 'error');
                    console.error('Error:', error);
                });
        }

        // 创建纪念日卡片
        function createAnniversaryCard(anniversary) {
            const card = document.createElement('div');
            card.className = 'bg-white rounded-xl shadow-md overflow-hidden transition-transform hover:scale-[1.02] border border-gray-100';

            // 格式化日期显示
            const dateObj = new Date(anniversary.date);
            const formattedDate = `${dateObj.getFullYear()}年${dateObj.getMonth() + 1}月${dateObj.getDate()}日`;

            // 计算天数显示文本
            let daysText = '';
            if (anniversary.days_until === 0) {
                daysText = '<span class="text-red-500 font-medium">今天</span>';
            } else if (anniversary.days_until === 1) {
                daysText = '明天';
            } else if (anniversary.days_until < 30) {
                daysText = `${anniversary.days_until}天后`;
            } else {
                const months = Math.floor(anniversary.days_until / 30);
                daysText = `${months}个月后`;
            }

            // 为爱情开始类型添加特殊标识
            const typeBadge = anniversary.type === 'love_start'
                ? '<span class="ml-2 px-2 py-0.5 bg-red-100 text-red-800 text-xs rounded-full">爱情起点</span>'
                : '';

            // 设置卡片内容
            card.innerHTML = `
                <div class="p-5">
                    <div class="flex justify-between items-start mb-3">
                        <h3 class="font-bold text-lg text-gray-800">${anniversary.title}${typeBadge}</h3>
                        <div class="relative">
                            <button class="text-gray-400 hover:text-gray-600" data-id="${anniversary.id}">
                                <i class="fa fa-ellipsis-v"></i>
                            </button>
                            <div class="hidden absolute right-0 mt-2 w-36 bg-white rounded-md shadow-lg py-1 z-10 anniversary-actions">
                                <button onclick="editAnniversary(${anniversary.id})" class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                    <i class="fa fa-pencil mr-2"></i>编辑
                                </button>
                                <button onclick="openDeleteModal(${anniversary.id})" class="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-gray-100">
                                    <i class="fa fa-trash mr-2"></i>删除
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="mb-4">
                        <p class="text-gray-500 text-sm">
                            <i class="fa fa-calendar mr-1"></i> ${formattedDate}
                        </p>
                        ${anniversary.type ? `<p class="text-gray-500 text-sm mt-1">
                            <i class="fa fa-tag mr-1"></i> ${anniversary.type === 'love_start' ? '关系确定日' : anniversary.type}
                        </p>` : ''}
                    </div>

                    ${anniversary.description ? `<p class="text-gray-600 text-sm mb-4">${anniversary.description}</p>` : ''}

                    <div class="pt-3 border-t border-gray-100">
                        <p class="text-sm text-primary font-medium">
                            <i class="fa fa-clock-o mr-1"></i> ${daysText} 是这个纪念日
                        </p>
                    </div>
                </div>
            `;

            // 添加点击事件显示操作菜单
            const actionButton = card.querySelector('button[data-id]');
            if (actionButton) {
                actionButton.addEventListener('click', function(e) {
                    e.stopPropagation();
                    // 关闭其他所有操作菜单
                    document.querySelectorAll('.anniversary-actions').forEach(el => {
                        el.classList.add('hidden');
                    });
                    // 显示当前操作菜单
                    this.nextElementSibling.classList.toggle('hidden');
                });
            }

            return card;
        }

        // 打开添加/编辑纪念日模态框
        function openAnniversaryModal(anniversaryId = null) {
            // 重置表单
            if (anniversaryForm) anniversaryForm.reset();
            const anniversaryIdEl = document.getElementById('anniversary-id');
            if (anniversaryIdEl) anniversaryIdEl.value = '';
            if (modalTitle) modalTitle.textContent = '添加共同纪念日';

            if (anniversaryId) {
                // 编辑模式 - 获取纪念日详情
                fetch(`/api/couple/shared-anniversaries/${anniversaryId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.anniversary) {
                            if (modalTitle) modalTitle.textContent = '编辑共同纪念日';
                            if (anniversaryIdEl) anniversaryIdEl.value = data.anniversary.id;

                            const titleEl = document.getElementById('title');
                            if (titleEl) titleEl.value = data.anniversary.title;

                            const dateEl = document.getElementById('date');
                            if (dateEl) dateEl.value = data.anniversary.date;

                            const typeEl = document.getElementById('type');
                            if (typeEl) typeEl.value = data.anniversary.type || '';

                            const descriptionEl = document.getElementById('description');
                            if (descriptionEl) descriptionEl.value = data.anniversary.description || '';
                        }
                    })
                    .catch(error => {
                        showNotification('获取纪念日详情失败', 'error');
                        console.error('Error:', error);
                    });
            }

            if (anniversaryModal) anniversaryModal.classList.remove('hidden');
        }

        // 关闭纪念日模态框
        function closeAnniversaryModal() {
            if (anniversaryModal) anniversaryModal.classList.add('hidden');
        }

        // 编辑纪念日
        function editAnniversary(anniversaryId) {
            openAnniversaryModal(anniversaryId);
        }

        // 打开删除模态框
        function openDeleteModal(anniversaryId) {
            const deleteAnnivIdEl = document.getElementById('delete-anniv-id');
            if (deleteAnnivIdEl) deleteAnnivIdEl.value = anniversaryId;
            if (deleteModal) deleteModal.classList.remove('hidden');
        }

        // 关闭删除模态框
        function closeDeleteModal() {
            if (deleteModal) deleteModal.classList.add('hidden');
        }

        // 处理保存纪念日
        function handleSaveAnniversary(e) {
            e.preventDefault();

            const anniversaryIdEl = document.getElementById('anniversary-id');
            const anniversaryId = anniversaryIdEl ? anniversaryIdEl.value : null;

            const titleEl = document.getElementById('title');
            const dateEl = document.getElementById('date');
            const typeEl = document.getElementById('type');
            const descriptionEl = document.getElementById('description');

            // 验证元素是否存在
            if (!titleEl || !dateEl) {
                showNotification('表单元素缺失', 'error');
                return;
            }

            const data = {
                title: titleEl.value.trim(),
                date: dateEl.value,
                type: typeEl ? typeEl.value : '',
                description: descriptionEl ? descriptionEl.value.trim() : ''
            };

            // 验证表单
            if (!data.title) {
                showNotification('请输入纪念日名称', 'error');
                return;
            }

            if (!data.date) {
                showNotification('请选择日期', 'error');
                return;
            }

            // 对于爱情开始类型，设置默认标题
            if (data.type === 'love_start' && !data.title) {
                data.title = '我们在一起了';
            }

            // 确定请求方法和URL
            const method = anniversaryId ? 'PUT' : 'POST';
            const url = anniversaryId
                ? `/api/couple/shared-anniversaries/${anniversaryId}`
                : '/api/couple/shared-anniversaries';

            // 发送请求
            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showNotification(data.message, 'success');
                    closeAnniversaryModal();
                    loadSharedAnniversaries();
                } else {
                    showNotification(data.message || '操作失败', 'error');
                }
            })
            .catch(error => {
                showNotification('保存失败', 'error');
                console.error('Error:', error);
            });
        }

        // 处理删除
        function handleDelete() {
            const deleteAnnivIdEl = document.getElementById('delete-anniv-id');
            if (!deleteAnnivIdEl) {
                showNotification('删除操作失败', 'error');
                return;
            }

            const anniversaryId = deleteAnnivIdEl.value;

            // 特别处理爱情开始纪念日的删除
            fetch(`/api/couple/shared-anniversaries/${anniversaryId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.anniversary && data.anniversary.type === 'love_start') {
                        if (!confirm('确定要删除爱情关系确定纪念日吗？这是你们关系的重要记录。')) {
                            return;
                        }
                    }

                    // 执行删除操作
                    return fetch(`/api/couple/shared-anniversaries/${anniversaryId}`, {
                        method: 'DELETE'
                    }).then(response => response.json());
                })
                .then(data => {
                    if (data && data.status === 'success') {
                        showNotification(data.message, 'success');
                        closeDeleteModal();
                        loadSharedAnniversaries();
                    } else if (data) {
                        showNotification(data.message || '删除失败', 'error');
                    }
                })
                .catch(error => {
                    showNotification('删除失败', 'error');
                    console.error('Error:', error);
                });
        }

        // 发送情侣请求
        function handleSendRequest(e) {
            e.preventDefault();

            const receiverUsername = document.getElementById('receiver-username').value.trim();
            const message = document.getElementById('request-message').value.trim();

            if (!receiverUsername) {
                showNotification('请输入对方账号', 'error');
                return;
            }

            fetch('/api/couple/request', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    receiver_username: receiverUsername,
                    message: message
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showNotification('请求发送成功', 'success');
                    closeRequestModal();
                    loadCoupleRequests();
                    requestForm.reset();
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                showNotification('发送请求失败', 'error');
                console.error('Error:', error);
            });
        }

        // 回应请求
        function respondToRequest(requestId, action) {
            // 先禁用按钮防止重复点击
            const acceptBtn = document.querySelector(`button[onclick="respondToRequest(${requestId}, 'accept')"]`);
            const rejectBtn = document.querySelector(`button[onclick="respondToRequest(${requestId}, 'reject')"]`);

            if (acceptBtn) acceptBtn.disabled = true;
            if (rejectBtn) rejectBtn.disabled = true;

            fetch(`/api/couple/request/${requestId}/respond`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ action: action })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showNotification(data.message, 'success');
                    loadCoupleRequests(); // 重新加载请求列表
                    checkRelationshipStatus(); // 更新关系状态
                } else {
                    showNotification(data.message, 'error');
                    // 恢复按钮状态
                    if (acceptBtn) acceptBtn.disabled = false;
                    if (rejectBtn) rejectBtn.disabled = false;
                }
            })
            .catch(error => {
                showNotification('处理请求失败', 'error');
                console.error('Error:', error);
                // 恢复按钮状态
                if (acceptBtn) acceptBtn.disabled = false;
                if (rejectBtn) rejectBtn.disabled = false;
            });
        }

        // 取消请求
        function cancelRequest(requestId) {
            if (confirm('确定要取消请求吗？')) {
                fetch(`/api/couple/request/${requestId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        showNotification('请求已取消', 'success');
                        loadCoupleRequests(); // 重新加载请求列表
                    } else {
                        showNotification(data.message, 'error');
                    }
                })
                .catch(error => {
                    showNotification('取消请求失败', 'error');
                    console.error('Error:', error);
                });
            }
        }

        // 解除情侣关系
        function endRelationship() {
            fetch('/api/couple/relationship', {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    showNotification(data.message, 'success');
                    closeConfirmModal();
                    checkRelationshipStatus();
                    loadCoupleRequests();
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                showNotification('解除关系失败', 'error');
                console.error('Error:', error);
            });
        }

        // 模态框控制
        function openRequestModal() {
            requestModal.classList.remove('hidden');
        }

        function closeRequestModal() {
            requestModal.classList.add('hidden');
        }

        function openConfirmModal() {
            confirmModal.classList.remove('hidden');
        }

        function closeConfirmModal() {
            confirmModal.classList.add('hidden');
        }

        // 显示通知
        function showNotification(message, type) {
            const notification = document.getElementById('notification');
            const icon = document.getElementById('notification-icon');
            const messageEl = document.getElementById('notification-message');

            if (!notification || !icon || !messageEl) return;

            // 设置通知类型样式
            if (type === 'success') {
                notification.className = 'fixed bottom-4 right-4 px-6 py-3 bg-green-50 text-green-700 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50';
                icon.className = 'fa fa-check-circle mr-2';
            } else {
                notification.className = 'fixed bottom-4 right-4 px-6 py-3 bg-red-50 text-red-700 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50';
                icon.className = 'fa fa-exclamation-circle mr-2';
            }

            // 设置消息内容并显示
            messageEl.textContent = message;
            notification.classList.remove('translate-y-20', 'opacity-0');
            notification.classList.add('translate-y-0', 'opacity-100');

            // 3秒后隐藏
            setTimeout(() => {
                notification.classList.remove('translate-y-0', 'opacity-100');
                notification.classList.add('translate-y-20', 'opacity-0');
            }, 3000);
        }





        const currentUserId = "{{ session['user_id'] }}";
        // 模态框控制
        const profileModal = document.getElementById('profile-modal');
        const openProfileBtn = document.getElementById('open-profile');
        const closeModalBtn = document.getElementById('close-modal');

        openProfileBtn.addEventListener('click', function(e) {
            e.preventDefault();
            profileModal.classList.remove('hidden');
        });

        closeModalBtn.addEventListener('click', function() {
            profileModal.classList.add('hidden');
        });

        // 点击模态框外部关闭
        profileModal.addEventListener('click', function(e) {
            if (e.target === profileModal) {
                profileModal.classList.add('hidden');
            }
        });

        // 保存昵称修改
        document.getElementById('save-profile').addEventListener('click', function() {
            const newNickname = document.getElementById('nickname').value.trim();

            if (!newNickname) {
                alert('昵称不能为空');
                return;
            }

            fetch(`/api/users/${currentUserId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ nickname: newNickname })
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(data => {
                        throw new Error(data.message || '修改失败');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.status === 'success') {
                    alert('昵称修改成功');
                    profileModal.classList.add('hidden');
                    // 可以在这里更新页面上显示的昵称
                    updateDisplayedNickname(newNickname);
                }
            })
            .catch(error => {
                alert(error.message);
                console.error('修改昵称时出错:', error);
            });
        });

        // 更新页面上显示的昵称（根据你的页面结构调整）
        function updateDisplayedNickname(nickname) {
            const nicknameElements = document.querySelectorAll('.user-nickname');
            nicknameElements.forEach(el => {
                el.textContent = nickname;
            });
        }




</script>
</body>
</html>
